package com.xjnt.tvos.tvlibs.jsbridge.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 传递数据参数处理
 * Created by caoyong on 18-1-10.
 */
class ParamData extends BasicParam {
    ParamData(String paramName, Class<?> paramClass) {
        super(paramName, paramClass);
    }

    @Override
    Object getValue(DataBuilder dataBuilder) {
        if (isDirectPutInJSON(getParamClass())) {
            return dataBuilder.get(getParamName(), getParamClass());
        } else {
            return JSON.toJavaObject(dataBuilder.get(getParamName(), JSONObject.class), getParamClass());
        }
    }

    @Override
    void setValue(DataBuilder dataBuilder, Object value) {
        if (isDirectPutInJSON(value)) {
            dataBuilder.put(getParamName(), value);
        } else {
            dataBuilder.put(getParamName(), JSON.toJSON(value));
        }
    }

    private boolean isDirectPutInJSON(Class type) {
        return (type.isPrimitive() || type == String.class || type == JSONArray.class || type == JSONObject.class);
    }

    private boolean isDirectPutInJSON(Object obj) {
        return (obj instanceof String || obj instanceof Integer || obj instanceof Long ||
                obj instanceof Float || obj instanceof Double || obj instanceof Boolean ||
                obj instanceof JSONArray || obj instanceof JSONObject);
    }
}
